//
//  XMChangeIcon.swift
//  sinaDemo
//
//  Created by Xueming on 2022/1/20.
//
/*
 1. 配置icon
 添加图片icon
 动态修改的icon不能放在 Assets.xcassets 里，但是正常的主icon还是可以在这里设置的，也可以按下面的方法来设置；
 首先，把需要修改的icon放在一个文件夹内：
 配置info.plist
 在info.plist中右键 -> Add Row ：
 输入Icon... 会有提示，选择Icon files（iOS 5）
 在 Icon files（iOS 5）内添加一个Key： CFBundleAlternateIcons ，类型为字典，在这个字典里配置我们所有需要动态修改的icon：键为icon的名称，值为一个字典（这个字典里包含两个键：CFBundleIconFiles，其值类型为Array，内容为icon的名称；UIPrerenderedIcon，其值类型为bool，内容为NO，也可以不加此key）
 如果是添加了多个尺寸icon，也要在这里分别配置，
 在设置icon的时候，会有个系统弹框，这样有时候会不太友好，我们可以使用Runtime，对UIViewController进行扩展来隐藏这个弹框
 */

import Foundation
import UIKit

/*给控制器写了个拓展，可以在appdelegate里调用一次*/
extension UIViewController {
    
    class func loadRuntimeSwizlingM() {
        let presentM:Method = class_getInstanceMethod(self.classForCoder(), #selector(present(_:animated:completion:)))!
        let presentSwizlingM = class_getInstanceMethod(self.classForCoder(), #selector(xm_presentViewCTR(_:animated:completion:)))!
        method_exchangeImplementations(presentM, presentSwizlingM)
    }
    @objc private func xm_presentViewCTR(_ viewControllerToPresent:UIViewController,animated:Bool,completion:()->Void) {
        if (viewControllerToPresent.isKind(of: UIAlertController.classForCoder())){
            let alertController:UIAlertController = viewControllerToPresent as! UIAlertController
            if (alertController.title == nil && alertController.message == nil && alertController.preferredStyle == .alert){
                return
            }
        }
        //!!!: 此时已经进行了方法交换，再次调用xm_present就相当于调用了系统的present方法。
        xm_presentViewCTR(viewControllerToPresent, animated: animated, completion: completion)
    }
}
class XMChangeIcon: UIViewController {
    lazy var HIconBtn:UIButton = UIButton(title: "切换HIcon", font: 15, backColor: .orange).then({
        $0.frame = CGRect(x: kScreenWidth/2 - 100, y: kNavigationHeight + 20, width: 200, height: 50)
        $0.addTarget(self, action: #selector(self.changeHIconClick), for: .touchUpInside)
    })
    lazy var VIconBtn = UIButton(title: "切换VIcon", font: 15, backColor: .orange).then({
        $0.frame = CGRect(x: kScreenWidth/2 - 100, y: HIconBtn.bottom + 10, width: 200, height: 50)
        $0.addTarget(self, action: #selector(self.changeVIconClick), for: .touchUpInside)
    })
    lazy var SinaIconBtn = UIButton(title: "切换原始主Icon", font: 15, backColor: .orange).then({
        $0.frame = CGRect(x: kScreenWidth/2 - 100, y: VIconBtn.bottom + 10, width: 200, height: 50)
        $0.addTarget(self, action: #selector(self.changeSinaIconClick), for: .touchUpInside)
    })
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        setUpUI()
        loadRuntime()
        // Do any additional setup after loading the view.
    }
    deinit {
        print("XMChangeIcon deinit")
        //退出当前控制器后将方法再交换回来
        loadRuntime()
    }
    private func setUpUI(){
        view.addSubview(HIconBtn)
        view.addSubview(VIconBtn)
        view.addSubview(SinaIconBtn)
    }
    @objc private func changeHIconClick(){
        changeAppIconWithName(iconName: "HMathJia")
    }
    @objc private func changeVIconClick(){
        changeAppIconWithName(iconName: "VMathJia")
    }
    @objc private func changeSinaIconClick(){
        changeAppIconWithName(iconName: nil)
    }
    private func changeAppIconWithName(iconName:String?){
       
        UIApplication.shared.setAlternateIconName(iconName) { error in
            if (error != nil) {
                print(error ?? "")
            }else {
                print("切换AppIcon 成功")
            }
            
        }
    }
}
//MARK: 利用runtime 来阻止系统提示换了icon 的弹框
extension XMChangeIcon {
    private func loadRuntime() {
        let presentM:Method = class_getInstanceMethod(self.classForCoder, #selector(present(_:animated:completion:)))!
        let presentSwizlingM = class_getInstanceMethod(self.classForCoder, #selector(xm_present(_:animated:completion:)))!
        method_exchangeImplementations(presentM, presentSwizlingM)
    }
    @objc private func xm_present(_ viewControllerToPresent:UIViewController,animated:Bool,completion:()->Void) {
        if (viewControllerToPresent.isKind(of: UIAlertController.classForCoder())){
            let alertController:UIAlertController = viewControllerToPresent as! UIAlertController
            if (alertController.title == nil && alertController.message == nil && alertController.preferredStyle == .alert){
                return
            }
        }
        //!!!: 此时已经进行了方法交换，再次调用xm_present就相当于调用了系统的present方法。
        xm_present(viewControllerToPresent, animated: animated, completion: completion)
    }
}
